package com.wjcxf.view;



import com.wjcxf.entry.DeviceEntry;
import com.wjcxf.paint.PaintGrid;
import com.wjcxf.utils.PropertiesUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
/**
 * @author 我叫程晓非
 * @desc 截图JPanel
 * @date 2022-03-15
 * @version 1.0
 */
public class ScreenshotPanel extends JPanel implements MouseListener, MouseMotionListener {
    public static float scale = 1.0f;
    public static int padding = 0;
    public static int x;
    public static int y;
    public static int width;
    public static int height;
    public static int PANEL_WIDTH;
    public static int PANEL_HEIGHT;
    int gridX;
    int gridY;
    int gridWidth;
    int gridHeight;


    boolean isFlush = false;
    Image img = null;
    public int imgWidth;
    public int imgHeight;

    private DeviceEntry<String,String> deviceEntry;
    // 定位网格
    private  PaintGrid grid;
    private static final String CONFIG_FILE = "./"+MainFrame.USER_CONFIG_FOLDER+"/"+"default"+MainFrame.USER_CONFIG_SUFFIX;
    public ScreenshotPanel(){//construct
        super();



        addMouseListener(this);
        addMouseMotionListener(this);

        //读取配置
        String gridXStr = PropertiesUtil.readValue(CONFIG_FILE,"grid.x");
        String gridYStr = PropertiesUtil.readValue(CONFIG_FILE,"grid.y");
        String gridWidthStr = PropertiesUtil.readValue(CONFIG_FILE,"grid.width");
        String gridHeightStr = PropertiesUtil.readValue(CONFIG_FILE,"grid.height");

        gridWidth = Integer.parseInt(gridWidthStr);
        gridHeight = Integer.parseInt(gridHeightStr);
//        gridX = Integer.parseInt(gridXStr);
//        gridY = Integer.parseInt(gridYStr);
//        if(gridX == 0){
//            gridX = (panelWidth - gridWidth)/2;
//
//        }
//        if(gridY == 0){
//            gridY = (panelHeight - gridHeight)/2;
//        }
        this.grid = new PaintGrid(gridX,gridY,gridHeight,gridWidth,Color.BLACK);


    }

    public void setDeviceEntry(DeviceEntry<String,String> deviceEntry){
        this.deviceEntry = deviceEntry;
        this.getGrid().setDeviceEntry(this.deviceEntry);
        isFlush = true;
        repaint();
    }

    public Image getImg(){
        return this.img;
    }
    @Override
    public void paint(Graphics g) {

        super.paint(g);
        g.setColor(getBackground());
        g.fillRect(0,0,getWidth(),getHeight());
        Graphics oldGraphics = g;
        if(deviceEntry!=null &&!"0".equals(this.deviceEntry.getKey())){
//            long start = System.currentTimeMillis();
            File file = new File("./"+MainFrame.USER_SCREENSHOT_FOLDER+"/"+this.deviceEntry.getKey()+".png");
            if(!file.exists()){
                System.out.println("图片文件不存在");
                return;
            }

            img =  Toolkit.getDefaultToolkit().getImage(file.getAbsolutePath());

            int imageWidth = img.getWidth(this);
            int imageHeight = img.getHeight(this);
            int panelWidth = this.getWidth();
            int panelHeight = this.getHeight();
            height = panelHeight - 2*padding;
            //这里丢失了精度
            scale = imageHeight/(float)height;
            this.grid.setScale(scale);
            width = (int)(imageWidth/scale);
            imgWidth = (int)(imageWidth/scale);
            imgHeight = panelHeight - 2*padding;
            y = padding;
            x = (panelWidth - width)/2;
            this.grid.setImgX(x);
            this.grid.setImgY(y);

//            long end = System.currentTimeMillis();
            if(img != null && isFlush){
                img.flush();
                isFlush = false;
            }
        }

        if(bufferedImage != null){
            g.drawImage(bufferedImage,x,y,imgWidth,imgHeight,null);
//            g.drawImage(bufferedImage,0,0,this.getWidth(),this.getHeight(),null);
        }
        grid.draw(g);
    }
    public BufferedImage getBufferedImage(){
        return this.bufferedImage;
    }
    public int getImageX(){
        return x;
    }
    public int getImageY(){
        return y;
    }
    public float getScale(){
        return scale;
    }
    public void paintComponent(Graphics g){
        super.paintComponent(g);
//        g.setColor(getBackground());
//        if(this.deviceEntry!=null && !"0".equals(this.deviceEntry.getKey())){
//            ImageIcon icon=new ImageIcon("./"+MainFrame.USER_SCREENSHOT_FOLDER+"/"+this.deviceEntry.getKey()+".png");
//            g.drawImage(icon.getImage(), x,y, width, height, this);
//        }


    }

    private boolean isSelectedGrid = false;
    private int startX;
    private int startY;
    private int deltaX;
    private int deltaY;
    private BufferedImage bufferedImage;
    public void setBufferedImage(BufferedImage bufferedImage){
        this.bufferedImage = bufferedImage;
        this.grid.setBufferedImage(bufferedImage);
        repaint();
    }
    @Override
    public void mouseClicked(MouseEvent e) {

        if(deviceEntry==null || "0".equals(this.deviceEntry.getKey())){
            JOptionPane.showMessageDialog(null, "请选择设备后操作", "提示",JOptionPane.ERROR_MESSAGE);
            return;
        }
        Point point = e.getPoint();
        startX = point.x;
        startY = point.y;
        System.out.println(this.getGrid().isShowTips());
        if(this.getGrid().isShowTips()){
            Rectangle tipsRectangle = getGrid().getTipsRect();
            System.out.println(tipsRectangle);
            if(tipsRectangle.contains(point.x,point.y)){
                this.getGrid().nextTips();
            }
            repaint();
            return;
        }

        Rectangle gridRectangle = getGridRect();

        if(gridRectangle.contains(point.x,point.y)){
            deltaX = this.grid.getX() - startX;
            deltaY = this.grid.getY() - startY;
            isSelectedGrid = true;
        }else{
            isSelectedGrid = false;
        }


        if(isSelectedGrid){
            this.grid.setColor(new Color(255,0,0));
        }else{
            this.grid.setColor(new Color(1,1,1));
        }
        repaint();
    }

    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {
        if(deviceEntry==null || "0".equals(this.deviceEntry.getKey())){

            return;
        }
        if(this.getGrid().isShowTips()){
            repaint();
            return;
        }
        Point point = e.getPoint();
//        System.out.println(point.x+","+point.y);
        startX = point.x;
        startY = point.y;
        Rectangle gridRectangle = getGridRect();

        if(gridRectangle.contains(point.x,point.y)){
            deltaX = this.grid.getX() - startX;
            deltaY = this.grid.getY() - startY;
            isSelectedGrid = true;
        }else{
            isSelectedGrid = false;
        }

        if(isSelectedGrid){
            this.grid.setColor(new Color(255,0,0));
        }else{
            this.grid.setColor(new Color(1,1,1));
        }
        repaint();
    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }

    public void setGridX(int x) {
        this.gridX = x;
        this.grid.setX(x,ScreenshotPanel.x,this.imgWidth);
        repaint();
    }

    public PaintGrid getGrid() {
        return grid;
    }

    public void setGridY(int y) {
        this.gridY = y;
        this.grid.setY(y,ScreenshotPanel.y,this.imgHeight);
        repaint();
    }

    public void setGridWidth(int width) {
        this.gridWidth = width;
        this.grid.setWidth(width);
        repaint();

    }

    public void setGridHeight(int height) {
        this.gridHeight = height;
        this.grid.setHeight(height);
        repaint();
    }

    //用来判断是否选中grid
    public Rectangle getGridRect(){
        return new Rectangle(this.grid.getX(),this.grid.getY(),this.grid.getWidth(),this.grid.getHeight());
    }



    //拖拽功能
    @Override
    public void mouseDragged(MouseEvent e) {
        Point point = e.getPoint();
        if(this.getGrid().isShowTips()){
            repaint();
            return;
        }
        if(isSelectedGrid){
            int dx = point.x +deltaX;
            int dy = point.y +deltaY;
            this.grid.setX(dx,x,this.imgWidth);
            this.grid.setY(dy,y,this.imgHeight);
            repaint();
        }
    }

    public boolean isSelectedGrid() {
        return isSelectedGrid;
    }


    @Override
    public void mouseMoved(MouseEvent e) {

    }

    //双缓冲
    //@TODO JFrame源码里自己实现了双缓冲，但是有时候图片还是会闪屏，有时间我再解决吧
//    private Image iBuffer;
//    private Graphics gBuffer;
//    @Override
//    public void update(Graphics g) {
//        if(iBuffer==null)
//        {
//            iBuffer=createImage(this.getSize().width,this.getSize().height);
//            gBuffer=iBuffer.getGraphics();
//        }
//        gBuffer.setColor(getBackground());
//        gBuffer.fillRect(0,0,this.getSize().width,this.getSize().height);
//        paint(g);
//        g.drawImage(iBuffer,0,0,this);
//    }


}
